package com.heart.house.biz.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.heart.house.common.model.House;
import com.heart.house.common.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 热门房产
 *
 * @author Luo Zhen
 * @create 2019-06-27 10:45
 */
@Service
public class RecommandService {

    private static final String HOT_HOUSE_KEY = "hot_house";

    @Autowired
    private HouseService houseService;

    @Value("${redis.address}")
    private String host;
    @Value("${redis.auth}")
    private String auth;

    public void increase(Long id) {
        Jedis jedis = new Jedis(host);
        jedis.auth(auth);
        jedis.zincrby(HOT_HOUSE_KEY, 1.0D, id + "");
        jedis.zremrangeByRank(HOT_HOUSE_KEY, 10, -1);
        jedis.close();
    }

    /**
     * 返回最热房产id
     *
     * @return
     */
    public List<Long> getHot() {
        Jedis jedis = new Jedis(host);
        jedis.auth(auth);
        Set<String> idSet = jedis.zrevrange(HOT_HOUSE_KEY, 0, -1);
        jedis.close();
        List<Long> list = idSet.stream().map(Long::parseLong).collect(Collectors.toList());
        return list;
    }

    public List<House> getHostList(Integer size) {
        House query = new House();
        List<Long> list = getHot();
        list = list.subList(0, Math.min(list.size(), size));
        if (list.isEmpty()) {
            return Lists.newArrayList();
        }
        query.setIds(list);
        final List<Long> orderList = list;
        List<House> houses = houseService.queryAndSetImg(query, PageParams.build(size, 1));
        // 赋值以后对其排序
        Ordering<House> houseSort = Ordering.natural().onResultOf(hs -> {
            return orderList.indexOf(hs.getId());
        });
        return houseSort.sortedCopy(houses);
    }

    public List<House> getLastest() {
        House query = new House();
        query.setSort("create_time");
        List<House> list = houseService.queryAndSetImg(query, PageParams.build(8, 1));
        return list;
    }
}
